import cgi 
import os 
from google.appengine.ext.webapp import template
from google.appengine.api import users 
from google.appengine.ext import webapp 
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib2
import string

# Yahoo stock quote URL
URL = "http://quote.yahoo.com/d/quotes.csv?s=%s&f=snohgl1d1"

def getYahooStockData(stockid):
	stockid = str(stockid)
	try:
		if stockid:
			if stockid.startswith('0'):
				stockid = stockid+'.SZ'
			elif stockid.startswith('6'):
				stockid = stockid+'.SS'
		url = URL % stockid
		fp = urllib2.urlopen(url)
		try:
			data = fp.read()
		finally:
			fp.close()
	except urllib2.URLError,e:
		handleError(e)
	return data

class Stock(db.Model):
	user = db.UserProperty()
	code = db.IntegerProperty()
	name = db.StringProperty()

class MainPage(webapp.RequestHandler): 
    def get(self):
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
		template_values = {
			'url': url,
			'url_linktext': url_linktext,
		}
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))
		
class GetStockInfo(webapp.RequestHandler):
	def get(self):
		stockid = self.request.get('stockid')
		did = self.request.get('stockid')
		data = getYahooStockData(stockid)
		if stockid:
			if stockid.startswith('0'):
				stockid = 'sz'+stockid
			elif stockid.startswith('6'):
				stockid = 'sh'+stockid
		template_values = {
			'did':did,
			'stockid':stockid,
			'result':data,
			}
		path = os.path.join(os.path.dirname(__file__), 'stockinfo.html') 
		self.response.out.write(template.render(path, template_values))
		
class AddMyStock(webapp.RequestHandler):
	def get(self):
		stockid = self.request.get('stockid')
		if users.get_current_user():
			stock = Stock()
			stock.user = users.get_current_user()
			stock.code = string.atoi(stockid)
			data = getYahooStockData(stockid).split(",")
			stock.name = data[1]
			stock.put()
			self.redirect('/listmystock')
		else:
			self.redirect('/')
			

class ListMyStock(webapp.RequestHandler):
	def get(self):
		if users.get_current_user():
			stocks = Stock.gql(
			"WHERE user = :username",username=users.get_current_user())
			datas = []
			for stock in stocks:
				data = {getYahooStockData(stock.code):stock.key()}
				datas.append(data)
			template_values = {
				'stocks':datas,
				}
			path = os.path.join(os.path.dirname(__file__), 'mystocks.html') 
			self.response.out.write(template.render(path, template_values))
		else:
			self.redirect('/')
			
class DelMyStock(webapp.RequestHandler):
	def get(self):
		stockid = self.request.get('stockid')
		if users.get_current_user():
			stock = Stock.gql("WHERE code = :code",code=string.atoi(stockid))
			stock.delete()
			self.redirect('/listmystock')
		else:
			self.redirect('/listmystock')
		
application = webapp.WSGIApplication( 
                                     [('/', MainPage),
									 ('/getstockinfo',GetStockInfo),
									 ('/addmystock',AddMyStock),
									 ('/listmystock',ListMyStock)], 
                                     debug=True) 
 
def main(): 
    run_wsgi_app(application) 
 
if __name__ == "__main__": 
    main()
